<!--
    group: 发票管理
    name: 开票列表/开票详情
    item: 下载发票弹层
-->
<template>
  <a-modal
    :width="600"
    :footer="null"
    v-model="config.visible"
    @cancel="cancel"
  >
    <h3>请选择下载发票格式</h3>
    <a-form-model
      ref="ruleForm"
      :model="form"
      :rules="rules"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
    >
      <a-form-model-item label=" " :colon="false" prop="type">
        <a-checkbox-group v-model="form.type">
          <a-checkbox
            v-for="(item,index) in fileList" :key="index"
            :value="item.typeName" name="type"
            :disabled="item.disabled"
          >{{ item.typeName }}</a-checkbox>
        </a-checkbox-group>
      </a-form-model-item>
      <a-form-model-item :wrapper-col="{ offset: 6 }">
        <a-button type="primary" @click="onSubmit" class="btnsLarge">下载</a-button>
      </a-form-model-item>
    </a-form-model>
  </a-modal>
</template>

<script>
import { cloneObject } from '@/utils/util'
import { invoiceUploadFiles } from '@api/invoiceAdminister'

export default {
  name: 'invoiceDownloadFormat',
  props: ['config'],
  data(){
    return{
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      form: {
        type: [],
      },
      rules: {
        type: [{ type: 'array', required: true, message: '请选择下载发票格式', trigger: 'change', }],
      },
      //文件类型: 126_PDF 127_0FD 128_XML 120_其他
      fileList: [
        {
          "typeName": "PDF",
          "fileType": 126,
          "disabled": true,
        },
        {
          "typeName": "OFD",
          "fileType": 127,
          "disabled": true,
        },
        {
          "typeName": "XML",
          "fileType": 128,
          "disabled": true,
        },
        {
          "typeName": "其他",
          "fileType": 120,
          "disabled": true,
        }
      ],
    }
  },
  watch: {
    'config.visible': function(newVal,oldVal){
      console.log(888,newVal,oldVal)
      if (newVal){
        //获取发票格式与地址
        this.getDownLoadInfo();
      }
    },
    'config.id': function(newVal,oldVal){
        // console.log(333,newVal,oldVal)
        // if (val.visible){
        //获取发票格式与地址
        this.getDownLoadInfo(newVal);
        // }
    },
  },
  methods: {
    //关闭重置数据
    cancel(){
      this.fileList = [
        {
          "typeName": "PDF",
          "fileType": 126,
          "disabled": true,
        },
        {
          "typeName": "OFD",
          "fileType": 127,
          "disabled": true,
        },
        {
          "typeName": "XML",
          "fileType": 128,
          "disabled": true,
        },
        {
          "typeName": "其他",
          "fileType": 120,
          "disabled": true,
        }
      ];

      this.$emit('handleInvoiceCancle')
    },
    //提交
    onSubmit() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          //处理发票格式
          let downArr = this.form.type;
          if (downArr && downArr.length > 0){
            for (let i = 0; i < downArr.length; i++) {
              for (let j = 0; j < this.fileList.length; j++) {
                if (this.fileList[j].typeName == downArr[i]){
                  //调用下载方法
                  // console.log('调用下载方法==>',this.fileList[j].fileName,this.fileList[j].fileUrl)
                  this.downLoad(this.fileList[j].fileName,this.fileList[j].fileUrl,this.fileList[j].fileType);

                  this.$nextTick(()=>{
                    this.config.visible = false;
                  })
                  this.$refs.ruleForm.resetFields();
                }
              }
            }
          }
        } else {
          return false;
        }
      });
    },
    //下载
    downLoad(name,url,type){
      let fileName = name || '发票';
      if (!url) {
        return false;
      }

      fetch(url).then(res => res.blob()).then(blob => {
        const newUrl = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.setAttribute('href', newUrl);
        link.setAttribute('download', fileName);
        link.click();
      })

      //fileType 文件类型: 126_PDF 127_0FD 128_XML 120_其他
      // if (type == 127){
      //   let a = document.createElement("a"); //创建一个<a></a>标签
      //   a.href = url; // 给a标签的href属性值加上地址，注意，这里是绝对路径，不用加 点.
      //   a.download = fileName; //设置下载文件文件名，这里加上.xlsx指定文件类型，pdf文件就指定.fpd即可
      //
      //
      //   a.style.display = "none"; // 障眼法藏起来a标签
      //   document.body.appendChild(a); // 将a标签追加到文档对象中
      //   // a.click(); // 模拟点击了a标签，会触发a标签的href的读取，浏览器就会自动下载了
      //   // a.remove(); // 一次性的，用完就删除a标签
      // }else {
      //   fetch(url).then(res => res.blob()).then(blob => {
      //     const newUrl = window.URL.createObjectURL(blob);
      //     const link = document.createElement('a');
      //     link.href = newUrl;
      //     link.download = fileName;
      //     link.click();
      //
      //     // link.setAttribute('download', fileName);
      //     // document.body.appendChild(link);
      //   })
      //
      // }

    },
    //获取发票格式与地址
    getDownLoadInfo(id){
      let params = {};
      params.taxId = id || this.config.id;
      invoiceUploadFiles(params).then(res => {
        if (res.success) {
          let arr = res.result || [];
          //处理比对数据
          if (arr.length > 0){
            for (let i = 0; i < arr.length; i++) {
              for (let j = 0; j < this.fileList.length; j++) {
                if (arr[i].fileType == this.fileList[j].fileType){
                  this.fileList[j].disabled = false;
                  this.fileList[j].fileName = arr[i].fileName;
                  this.fileList[j].fileUrl = arr[i].fileUrl;
                }
              }
            }
          }


        }else{
          this.$message.warning(res.message);
        }
      })
    },
  }
}
</script>

<style scoped lang="less">
h3{
  font-weight: bolder;
  margin-bottom: 30px;
}
</style>
